<template>
  <a-modal
    :open="open"
    title="添加分类"
    width="500px"
    @ok="handleSave"
    @cancel="handleCancel"
    :confirm-loading="loading"
    @update:open="(value: boolean) => emit('update:open', value)"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item label="分类名称" name="name">
        <a-input
          v-model:value="formData.name"
          placeholder="请输入分类名称"
          size="large"
        />
      </a-form-item>

      <a-form-item label="描述" name="description">
        <a-textarea
          v-model:value="formData.description"
          placeholder="请输入分类描述"
          :rows="3"
          size="large"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import type { FormInstance } from 'ant-design-vue';

// 类型定义
interface InspectionCategory {
  id: string;
  name: string;
  description?: string;
}

// Props
interface Props {
  open: boolean;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'update:open': [value: boolean];
  save: [category: InspectionCategory]
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const loading = ref(false);

// 表单数据
const formData = ref<Omit<InspectionCategory, 'id'>>({
  name: '',
  description: '',
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入分类名称',trigger: 'blur' }],
};

// 方法
const resetForm = () => {
  formData.value = {
    name: '',
    description: '',
  };
};

const handleSave = async () => {
  try {
    await formRef.value?.validate();
    loading.value = true;

    const category: InspectionCategory = {
      id: '',
      ...formData.value,
    };

    emit('save', category);
    emit('update:open', false);
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    loading.value = false;
  }
};

const handleCancel = () => {
  emit('update:open', false);
  resetForm();
};

// 监听props变化
watch(
  () => props.open,
  (newVal) => {
    if (newVal) {
      resetForm();
    }
  },
);
</script>

<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style>
